<template>
  <div class="flex flex-column height-100-percent">
    <div class="bg-white top">
      <div class="flex flex-row flex-nowrap width-100-vw">
        <div
          class="text-align-center padding-10 flex-1"
          v-for="item in zhishus"
          :key="item.code"
          @click="showChart(item)"
        >
          <div class="line-height-15">
            {{item.name}}
            <span class="iconfont icon-pan bolder"></span>
          </div>
          <div class="line-height-15" :class="item.chg > 0 ? 'red': 'green'">{{item.currentValue}}</div>
          <div class="font-size-13 line-height-15">
            <span
              :class="item.chg > 0 ? 'red': 'green'"
              class="padding-right-10"
            >{{item.chg >0 ? '+'+item.chg : item.chg}}</span>

            <span
              :class="item.chg > 0 ? 'red': 'green'"
            >{{item.chg > 0 ? '+'+item.chgPercent : item.chgPercent}}%</span>
          </div>
        </div>
      </div>
    </div>
    <van-pull-refresh class="flex-1 overflow-auto" v-model="isLoading" @refresh="onRefresh">
      <div class="content flex flex-1 flex-column overflow-auto">
        <div
          class="bg-white margin-bottom-10 padding-10 relative"
          v-for="item in datas"
          :key="item.code"
        >
          <div class="padding-left-20 padding-bottom-10 flex flex-row flex-middle">
            <van-icon name="label" type="field" color="#ebc613" size="25"></van-icon>
            <div class="bold line-height-1 padding-left-5">{{item.name}}</div>
            <div class="code line-height-1 padding-left-10">{{item.jijin_code}}</div>
          </div>

          <!-- 这里是列表 -->
          <div class="grid col-header">
            <div class="flex flex-row flex-center flex-middle">
              <van-icon name="underway-o" />
              <div class="line-height-1">改变时间</div>
            </div>

            <div class="line-height-1" style="margin-top:2px">累积涨跌幅</div>
            <div class="line-height-1" style="margin-top:2px">今日估值</div>

            <div class="flex flex-row flex-center flex-middle">
              <div class="line-height-1">趋势</div>
              <van-icon
                v-if="item.lastModify == today && item.trend_value == 1"
                name="warn-o"
                :color="item.trend_value === 1 ? 'red':'green'"
                size="16"
              ></van-icon>
            </div>
          </div>
          <div class="grid text-align-center padding-top-5 grid-item">
            <div>{{item.lastModify}}</div>
            <div
              :class="item.totalChg > 0 ? 'red': 'green'"
            >{{item.totalChg > 0 ? '+'+item.totalChg : item.totalChg}}%</div>

            <div
              :class="item.guzhi > 0 ? 'red': 'green'"
            >{{item.guzhi > 0 ? '+'+item.guzhi : item.guzhi}}%</div>

            <van-icon
              :name="item.trend_value == 1 ? 'success' : 'cross'"
              :color="item.trend_value == 1 ? 'red' : 'green'"
              size="20"
              style="margin-top:-2px"
            ></van-icon>
          </div>
        </div>
      </div>
    </van-pull-refresh>
    <div class="bg-white padding-10 warn code">特别声明：本文仅为趋势跟踪，不构成买卖建议，股市、基金有风险，投资需谨慎</div>
  </div>
</template>

<script>
import { ImagePreview } from 'vant'
import { http, jsonp, parseTime, showWarningToast, showSuccessToast, showLoading, hideLoading, sum } from '~utils'

export default {
  data () {
    return {
      isLoading: false,
      zhishus: [],
      datas: [],
      today: parseTime(null, '{y}-{m}-{d}')
    }
  },
  components: {
    [ImagePreview.Component.name]: ImagePreview.Component,
  },
  mounted () {
    this.getData()
  },
  activated () {
    document.title = '天气预报'
    this.getData()
  },
  deactivated () {
    this.isHide = true
  },
  methods: {
    async getData () {
      this.getZhishu()
      await this.getTrendData()

      if (this.interVal) {
        clearInterval(this.interVal)
      }

      this.interVal = setInterval(() => {
        this.getTrendData()
        this.getZhishu()
      }, 60 * 1000)
    },
    async getZhishu () {
      if (this.isHide) {
        return
      }
      let zhushucodes = ['sh000001', 'sz399001', 'sz399006']
      let datas = []

      let zhishus = await jsonp('https://hq.sinajs.cn/list=' + zhushucodes.join(','), { name: zhushucodes.map(item => 'hq_str_' + item), isFunction: false })
      zhishus.forEach((zhishu, index) => {
        if (!zhishu) {
          return
        }
        let data = zhishu.split(',')
        if (data && data.length) {
          let yestclose = data[2]
          let currentValue = Number(data[3] || yestclose).toFixed(2)
          let chg = Number(currentValue - yestclose).toFixed(2)
          let chgPercent = ((chg / yestclose) * 100).toFixed(2)
          datas.push({
            code: zhushucodes[index],
            name: data[0],
            yestclose,
            currentValue,
            chg,
            chgPercent
          })
        }
      })
      this.zhishus = datas
    },
    async getTrendData () {
      if (this.isHide) {
        return
      }
      let data
      // 检查缓存是否为今天数据
      let industrys = localStorage.getItem('industrys')
      if (industrys) {
        industrys = JSON.parse(industrys)
      }
      if (industrys && (industrys.date == this.today)) {
        // 不从后台请求
        data = industrys.data
      } else {
        let { result } = await this.$cloudbase.callFunction({ name: 'industryTrend' })
        data = result.datas
        localStorage.setItem('industrys', JSON.stringify({ date: this.today, data: data })) // 只缓存数据库数据
      }

      this.getIndustryTrendByFE({ industrys: data })
    },
    showChart (item) {
      ImagePreview([
        `http://image.sinajs.cn/newchart/min/n/${item.code}.gif`,
      ])
    },
    async getMa ({ industrys }) {

      let result = {}
      let end = new Date()
      let start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 35)

      end = parseTime(end, '{y}{m}{d}')
      start = parseTime(start, '{y}{m}{d}')

      for (let industry of industrys) {
        let { code } = industry
        let res = await jsonp(`https://q.stock.sohu.com/hisHq?code=cn_${code}&start=${start}&end=${end}&stat=1&order=D&period=d&callback=historySearchHandler&rt=jsonp`, { name: 'historySearchHandler' })
        result[code] = res
      }

      return result
    },
    async getTodayData ({ industrys }) {
      let codes = industrys.map(industry => (industry.type == 0 ? 'sh' : 'sz') + industry.code)
      return jsonp('https://hq.sinajs.cn/list=' + codes.join(','), { name: codes.map(item => 'hq_str_' + item), isFunction: false })
    },
    async getFundData ({ industrys }) {
      let codes = industrys.map(item => item.jijin_code)
      let res = await http({
        url: `https://fundmobapi.eastmoney.com/FundMNewApi/FundMNFInfo?pageIndex=1&pageSize=50&plat=Android&appType=ttjj&product=EFund&Version=1&deviceid=ssdfsdfsdf&Fcodes=${codes}`,
        method: 'get',
        loading: false
      })
      return res
    },
    fmtTodataData (data) {
      data = data.split(',')
      if (data && data.length) {
        let yestclose = data[2]
        let currentValue = Number(data[3] || yestclose).toFixed(2)
        return {
          currentValue,
          yestclose
        }
      }
      return {}
    },
    async getIndustryTrendByFE ({ industrys }) {
      // TODO
      let todayData = await this.getTodayData({ industrys }) // 股票实时价格
      // let maData = await this.getMa({ industrys }) // TODO:看看是否有优化空间
      let fundData = await this.getFundData({ industrys }) // 基金实时价格

      industrys.forEach((industry, index) => {
        let { code, trend_value } = industry
        let todayRes = todayData[index]
        // let maRes = maData[code][0].hq.map(item => Number(item[2]))
        let guzhi = fundData.Datas[index]

        let needUpdateTrend = false

        let { currentValue } = this.fmtTodataData(todayRes)


        industry.guzhi = guzhi.GSZZL

        industry.totalChg = (((currentValue - industry.lastPrice) / industry.lastPrice) * 100).toFixed(2)

        if (trend_value && ((currentValue < industry.ma20day_fix) && (currentValue < industry.ma5week_fix))) {
          industry.trend_value = 0
          needUpdateTrend = true
        }
        // 下降时 若满足条件则更新为下降
        if (!trend_value && ((currentValue >= industry.ma20day * 1.01) && (currentValue >= industry.ma5week * 1.01))) {
          industry.trend_value = 1
          needUpdateTrend = true
        }

        if (needUpdateTrend) {
          industry.lastPrice = currentValue
          industry.lastModify = parseTime(null, '{y}-{m}-{d}')
        }

      })

      this.datas = industrys
    },
    async onRefresh () {
      this.isLoading = true
      await this.getData()
      this.isLoading = false
    },

  }
}
</script>

<style>
img.van-image__img {
  background: #fff !important;
}
</style>

<style scoped>
.loading-mask {
  width: 100%;
  height: 100%;
  background: rgba(256, 256, 256, 0.8);
  top: 0;
  left: 0;
  text-align: center;
}

.bold {
  font-weight: bold;
}

.grid {
  display: grid;
  grid-template-columns: 35% 25% 25% 15%;
}

.grid-item {
  min-height: 32px;
}

.grid2 {
  display: grid;
  grid-template-columns: 25% 25% 25% 25%;
}

.grid-3 {
  display: grid;
  grid-template-columns: 33.3% 33.3% 33.3%;
}

.code {
  color: rgb(129, 129, 129);
  font-size: 13px;
}

.sign {
  margin-top: -5px;
}

.time {
  margin-top: -4px;
}

.col-header {
  color: rgb(129, 129, 129);
  font-size: 13px;
  line-height: 1;
  text-align: center;
  margin-bottom: 5px;
}

.title {
  background: rgb(235, 86, 92);
  color: #fff;
  line-height: 40px;
}

.warn {
  text-align: center;
  font-size: 14px;
}

.top {
  /* position: fixed; */
  height: 90px;
  z-index: 1;
  border-bottom: 1px solid #f6f6f6;
}

.content {
  /* padding-top: 90px; */
}
</style>